package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.*;
import com.java1234.service.OperationLogsService;
import com.java1234.service.SysRoleMenuService;
import com.java1234.service.SysRoleService;
import com.java1234.service.SysUserRoleService;
import com.java1234.util.IpUtil;
import com.java1234.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统角色Controller控制器
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private OperationLogsService operationlogsService;

    @Autowired
    private HttpServletRequest request; // 注入HttpServletRequest

    /**
     * 获取当前登录用户的用户名
     * @return 用户名
     */
    private String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }
    }
    /**
     * 查询所有角色信息
     */
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public R listAll() {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("查询所有角色信息");

        Map<String, Object> resultMap = new HashMap<>();
        List<SysRole> roleList = sysRoleService.list();
        resultMap.put("roleList", roleList);

        long endTime = System.currentTimeMillis(); // 记录操作结束时间
        long elapsedTime = endTime - startTime; // 计算耗时

        // 记录操作日志
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation("查询所有角色");
        log.setMethod("GET /sys/role/listAll");
        log.setParams("");
        log.setResult("成功");
        log.setElapsedTime(elapsedTime);
        log.setCreateTime(new Date());
        log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
        log.setStatus("OK");
        operationlogsService.logOperation(log);

        return R.ok(resultMap);
    }
    /**
     * 根据条件分页查询角色信息
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:query')")
    public R list(@RequestBody PageBean pageBean) {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("根据条件分页查询角色信息: {}", pageBean);
        String query = pageBean.getQuery().trim();

        Page<SysRole> pageResult = sysRoleService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),
                new QueryWrapper<SysRole>().like(StringUtil.isNotEmpty(query), "name", query));
        List<SysRole> roleList = pageResult.getRecords();

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", roleList);
        resultMap.put("total", pageResult.getTotal());

        long endTime = System.currentTimeMillis(); // 记录操作结束时间
        long elapsedTime = endTime - startTime; // 计算耗时

        // 记录操作日志
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation("分页查询角色");
        log.setMethod("POST /sys/role/list");
        log.setParams(pageBean.toString());
        log.setResult("成功");
        log.setElapsedTime(elapsedTime);
        log.setCreateTime(new Date());
        log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
        log.setStatus("OK");
        operationlogsService.logOperation(log);

        return R.ok(resultMap);
    }
    /**
     * 添加或修改角色信息
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add') || hasAuthority('system:role:edit')")
    public R save(@RequestBody SysRole sysRole) {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("添加或修改角色信息: {}", sysRole);
        if (sysRole.getId() == null || sysRole.getId() == -1) {
            sysRole.setCreateTime(new Date());
            sysRoleService.save(sysRole);

            // 记录操作日志
            Operationlogs log = new Operationlogs();
            log.setUsername(getCurrentUsername());
            log.setOperation("添加角色");
            log.setMethod("POST /sys/role/save");
            log.setParams(sysRole.toString());
            log.setResult("成功");
            log.setElapsedTime(System.currentTimeMillis() - startTime); // 计算耗时
            log.setCreateTime(new Date());
            log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
            log.setStatus("OK");
            operationlogsService.logOperation(log);
        } else {
            sysRole.setUpdateTime(new Date());
            sysRoleService.updateById(sysRole);

            // 记录操作日志
            Operationlogs log = new Operationlogs();
            log.setUsername(getCurrentUsername());
            log.setOperation("修改角色");
            log.setMethod("POST /sys/role/save");
            log.setParams(sysRole.toString());
            log.setResult("成功");
            log.setElapsedTime(System.currentTimeMillis() - startTime); // 计算耗时
            log.setCreateTime(new Date());
            log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
            log.setStatus("OK");
            operationlogsService.logOperation(log);
        }
        return R.ok();
    }
    /**
     * 根据ID查询角色信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public R findById(@PathVariable(value = "id") Integer id) {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("根据ID查询角色信息: {}", id);
        SysRole sysRole = sysRoleService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("sysRole", sysRole);

        long endTime = System.currentTimeMillis(); // 记录操作结束时间
        long elapsedTime = endTime - startTime; // 计算耗时

        // 记录操作日志
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation("查询角色");
        log.setMethod("GET /sys/role/{id}");
        log.setParams("ID: " + id);
        log.setResult("成功");
        log.setElapsedTime(elapsedTime);
        log.setCreateTime(new Date());
        log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
        log.setStatus("OK");
        operationlogsService.logOperation(log);

        return R.ok(map);
    }
    /**
     * 删除角色信息
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public R delete(@RequestBody Long[] ids) {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("删除角色信息: {}", Arrays.toString(ids));
        sysRoleService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", ids));

        long endTime = System.currentTimeMillis(); // 记录操作结束时间
        long elapsedTime = endTime - startTime; // 计算耗时

        // 记录操作日志
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation("删除角色");
        log.setMethod("POST /sys/role/delete");
        log.setParams(Arrays.toString(ids));
        log.setResult("成功");
        log.setElapsedTime(elapsedTime);
        log.setCreateTime(new Date());
        log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
        log.setStatus("OK");
        operationlogsService.logOperation(log);

        return R.ok();
    }
    /**
     * 查询角色的菜单信息
     */
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public R menus(@PathVariable(value = "id") Integer id) {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("查询角色 {} 的菜单信息", id);
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());

        long endTime = System.currentTimeMillis(); // 记录操作结束时间
        long elapsedTime = endTime - startTime; // 计算耗时

        // 记录操作日志
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation("查询角色菜单");
        log.setMethod("GET /sys/role/menus/{id}");
        log.setParams("ID: " + id);
        log.setResult("成功");
        log.setElapsedTime(elapsedTime);
        log.setCreateTime(new Date());
        log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
        log.setStatus("OK");
        operationlogsService.logOperation(log);

        return R.ok().put("menuIdList", menuIdList);
    }
    /**
     * 更新角色的菜单信息
     */
    @Transactional
    @PostMapping("/updateMenus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public R updateMenus(@PathVariable(value = "id") Long id, @RequestBody Long[] menuIds) {
        long startTime = System.currentTimeMillis(); // 记录操作开始时间
        logger.info("更新角色 {} 的菜单信息: {}", id, Arrays.toString(menuIds));
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId);
            sysRoleMenuList.add(roleMenu);
        });
        sysRoleMenuService.saveBatch(sysRoleMenuList);

        long endTime = System.currentTimeMillis(); // 记录操作结束时间
        long elapsedTime = endTime - startTime; // 计算耗时

        // 记录操作日志
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation("更新角色菜单");
        log.setMethod("POST /sys/role/updateMenus/{id}");
        log.setParams("Role ID: " + id + ", Menu IDs: " + Arrays.toString(menuIds));
        log.setResult("成功");
        log.setElapsedTime(elapsedTime);
        log.setCreateTime(new Date());
        log.setIpAddress(IpUtil.getIpAddr(request)); // 获取真实的客户端IP地址
        log.setStatus("OK");
        operationlogsService.logOperation(log);

        return R.ok();
    }
}